<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item prop="roleName" label="角色名称">
        <el-input v-model="queryForm.roleName" placeholder="请输入角色名称" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="roleKey" label="权限字符">
        <el-input v-model="queryForm.roleKey" placeholder="请输入权限字符" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="status" label="状态">
        <el-select v-model="queryForm.status" placeholder="请选择角色状态">
          <el-option :value="2" label="正常" />
          <el-option :value="1" label="停用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space>
          <el-button type="primary" @click="handleQuery" icon="Search"> 搜索</el-button>
          <el-button @click="handleResetQuery" icon="Refresh"> 重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <el-divider />

    <div class="action">
      <el-space>
        <el-button v-has="'admin:sysRole:add'" type="primary" @click="handleAdd" icon="Plus"> 新增</el-button>
        <el-button v-has="'admin:sysRole:remove'" type="primary" status="danger" @click="() => { deleteVisible = true; }"
          icon="Delete">批量删除</el-button>
        <el-button type="primary" status="warning" disabled icon="Download"> 导出</el-button>
      </el-space>
    </div>

    <el-table :data="tableData" row-key="roleId" table-layout="auto">
      <el-table-column label='编号' prop='roleId'></el-table-column>
      <el-table-column label='角色名称' prop='roleName'></el-table-column>
      <el-table-column label='权限字符' prop='roleKey'></el-table-column>
      <el-table-column label='排序' prop='roleSort'></el-table-column>
      <el-table-column label='状态' prop='status'>
        <template #default="scope">
          <el-tag v-if="scope.row.status == 2" type="success">正常</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label='创建时间' prop='createdAt'>
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label='操作' prop='action'>
        <template #default="scope">
          <el-space>
            <el-button v-has="'admin:sysRole:edit'" text type="primary" @click="handleUpdate(scope.row)"
              icon="Edit">修改</el-button>
            <el-button v-has="'admin:sysRole:update'" text type="primary" @click="handleDataScope(scope.row)"
              icon="CircleCheck"> 数据权限
            </el-button>
            <el-button v-has="'admin:sysRole:remove'" text type="primary"
              @click="() => { deleteVisible = true; deleteData = [scope.row.roleId];  }" icon="CircleCheck"> 删除
            </el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <!-- <PageTable :data="tableData" row-key="roleId" :page-index="currentPage" @page-change="reloadCurrent" :total="pager.count">
    </PageTable> -->

    <el-pagination :page-size="10" v-model="currentPage" layout="prev, pager, next" :total="pager.count"
      @current-change="handleQuery()" />

    <!-- Role Modal -->
    <el-dialog v-model="modalVisible" :title="title" title-align="start" @before-ok="handleBeforeOk"
      @close="handleCancel">
      <el-form :model="modalForm" :rules="rules" ref="modalFormRef">
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="modalForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey" label="权限字符">
          <el-input v-model="modalForm.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item prop="roleSort" label="角色排序">
          <el-input-number v-model="modalForm.roleSort" mode="button" :default-value="0" :style="{ width: '150px' }" />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="modalForm.status">
            <el-radio label="2">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限设置">
          <el-tree v-model:checked-keys="checkedKeys" :checkable="true" :check-strictly="false" :data="treeData"
            :default-expand-all="false" :field-names="{ key: 'id', title: 'label' }" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input type='textarea' v-model="modalForm.remark" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-row justify="end">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleBeforeOk">确认</el-button>
        </el-row>
      </template>
    </el-dialog>

    <!-- DataScope Modal -->
    <el-dialog v-model="scopedModalVisible" :title="title" title-align="start" @before-ok="handleScopeBeforeOk"
      @close="handleCancel">
      <el-form :model="scopeForm">
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="scopeForm.roleName" disabled />
        </el-form-item>
        <el-form-item prop="roleKey" label="权限字符">
          <el-input v-model="scopeForm.roleKey" disabled />
        </el-form-item>
        <el-form-item prop="dataScope" label="权限范围">
          <el-select v-model="scopeForm.dataScope" placeholder="请选择权限范围">
            <el-option v-for="item in dataScopeOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row justify="end">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleScopeBeforeOk">确认</el-button>
        </el-row>
      </template>
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="removeRole"
      @deleteVisibleChange="() => deleteVisible = false" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, getCurrentInstance, nextTick, watch } from 'vue';
import { getRole, addRole, updateRole, removeRole, updateRoleScoped, getRoleMenuTree } from '@/api/admin/role';
import { parseTime } from '@/utils/parseTime';


// Akiraka 20230210 删除数据
const deleteData = ref([])
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false)
// Akiraka 20230210 监听删除事件
watch(() => deleteVisible.value ,(value) => {
  if ( value == false ) {
    getRoleInfo({ ...pager, ...queryForm });
  }
})

const { proxy } = getCurrentInstance();

const currentPage = ref(1);
// Pager
const pager = {
  count: 0,
  pageIndex: 1,
  pageSize: 10,
};

// Batch Delete List
const batchDeleteList = ref([]);
const queryFormRef = ref({});
// Form
const queryForm = reactive({});
const modalFormRef = ref({});
const modalForm = reactive({
  sort: 0,
  status: '2',
});
const scopeForm = reactive({});

// rules
const rules = {
  roleName: [{ required: true, message: '请输入角色名称' }],
  roleKey: [{ required: true, message: '请输入权限字符' }],
};

// ScopeOption
const dataScopeOptions = [
  {
    value: '1',
    label: '全部数据权限',
  },
  {
    value: '2',
    label: '自定数据权限',
  },
  {
    value: '3',
    label: '本部门数据权限',
  },
  {
    value: '4',
    label: '本部门及以下数据权限',
  },
  {
    value: '5',
    label: '仅本人数据权限',
  },
];

// Table Data;
const tableData = ref([]);

// Tree Data;
const checkedKeys = ref([]);
const treeData = ref([]);

// Modal
const modalVisible = ref(false);
const scopedModalVisible = ref(false);
const title = ref('默认标题');

// Table Select
const handleSelect = (rowKey) => {
  batchDeleteList.value = rowKey;
};

// 查询
const handleQuery = async () => {
  const res = await getRole({ ...pager, ...queryForm });
  const { count, list, pageIndex, pageSize } = res.data;

  tableData.value = list;
  Object.assign(pager, { count, pageIndex, pageSize });
};

// 重置查询
const handleResetQuery = () => {
  queryFormRef.value.resetFields();
  getRoleInfo(queryForm);
};

// 创建
const handleAdd = () => {
  modalVisible.value = true;
  title.value = '创建角色';
};

// 修改角色
const handleUpdate = async (record) => {
  modalVisible.value = true;
  title.value = '修改角色';

  await nextTick();
  Object.assign(modalForm, record);

  // 显示勾选的菜单，checkedKeys 传入id数组即可
  const menuIdsChecked = [];
  record.sysMenu.forEach((item) => {
    menuIdsChecked.push(item.menuId);
  });
  checkedKeys.value = menuIdsChecked;
};

// 分配数据权限
const handleDataScope = async (record) => {
  scopedModalVisible.value = true;
  title.value = '分配数据权限';

  const { roleKey, roleName, dataScope, roleId } = record;
  await nextTick();
  Object.assign(scopeForm, { roleKey, roleName, dataScope, roleId });
};

/**
 * 分页改变
 * @param {Number} [page]
 */
const handlePageChange = (page) => {
  pager.pageIndex = page;

  // 修改当前页码
  currentPage.value = page;
  getRoleInfo({ ...pager, ...queryForm });
};

// 每页数据量
const handlePageSizeChange = (pageSize) => {
  pager.pageSize = pageSize;
  getRoleInfo({ ...pager, ...queryForm });
};

// 角色管理表单提交
// 异步关闭表单需要使用 done() 回调函数
const handleBeforeOk = (done) => {
  modalFormRef.value.validate(async (valid) => {
    // 如果 valid 为空则数据校验通过
    if (valid) {
      modalForm.menuIds = checkedKeys.value;
      let res;
      if (modalForm.roleId) {
        const { code, msg } = await updateRole(modalForm, modalForm.roleId);
        if (code == 200 ) {
          proxy.$message.success('更新成功');
        } else {
          proxy.$message.error(msg);
        }
      } else {
        const { code, msg } = await addRole(modalForm);
        if (code == 200 ) {
          proxy.$message.success('新增成功');
        } else {
          proxy.$message.error(msg);
        }
      }
      getRoleInfo();
      done();
    } else {
      proxy.$message.error('数据校验失败');
      done(false);
    }
  });
};

// 数据权限表单提交
const handleScopeBeforeOk = async (done) => {
  const res = await updateRoleScoped(scopeForm);
  proxy.$message.success(res.msg);
  done();

  getRoleInfo();
};

 // 重置数据表单
 const handleCancel = () => {
  modalVisible.value = false;
  modalForm.roleId = null;
  scopeForm.roleId = null;
  checkedKeys.value = [];
  modalFormRef.value.resetFields();
};

// 获取角色信息
const getRoleInfo = async (params = {}) => {
  const { data, code, msg } = await getRole(params);
  if ( code == 200 ) {
    tableData.value = data.list;
    Object.assign(pager, { count: data.count, pageIndex: data.pageIndex, pageSize: data.pageSize });
  } else {
    proxy.$message.error(msg);
  }
};

// 获取角色菜单信息
const getRoleMenuTreeInfo = async () => {
  const res = await getRoleMenuTree({}, 0);
  treeData.value = res.data.menus;
  checkedKeys.value = res.data.checkedKeys;
};

onMounted(async () => {
  getRoleInfo();
  getRoleMenuTreeInfo();
});
</script>

<style setup>
.action {
  margin-bottom: 12px;
}
</style>
